import 'package:app_router_demo/config/app_router.dart';
import 'package:app_router_demo/gen/app_images.dart';
import 'package:app_router_demo/login_tip_dialog.dart'; // 你的弹窗文件
import 'package:app_router_demo/providers/auth_provider.dart';
import 'package:auto_route/auto_route.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:provider/provider.dart';

@RoutePage()
class LoginIndexPage extends StatefulWidget {
  const LoginIndexPage({super.key});

  @override
  State<LoginIndexPage> createState() => _LoginIndexPageState();
}

class _LoginIndexPageState extends State<LoginIndexPage> {
  // 我们不再依赖 isChecked 状态来阻止按钮点击，而是根据其决定是否显示弹窗
  // onPressed 中直接根据 isChecked 状态判断
  // 如果 isChecked 为 false，则显示弹窗；如果为 true，则尝试跳转
  // 弹窗关闭后，如果 isChecked 变为 true，可以再次点击按钮进行跳转。

  void _showKindTipsDialog(BuildContext dialogContext) {
    showDialog(
      context: dialogContext,
      barrierDismissible: false,
      builder: (BuildContext context) {
        return KindTipsDialog(
          onDisagree: () {
            Navigator.of(context).pop();
            print('用户点击了 Disagree');
          },
          onAgree: () {
            // 在这里更新 isChecked 状态
            Provider.of<AuthProvider>(
              context,
              listen: false,
            ).setIsChecked(true);
            Navigator.of(context).pop(); // 关闭弹窗
            print('用户点击了 Agree，isChecked 已更新');
            // 注意：此时 isChecked 已更新，但用户需要再次点击手机登录按钮才能跳转
          },
          onServiceAgreementTap: () {
            print('点击了服务协议');
            // TODO: Launch URL
          },
          onPrivacyPolicyTap: () {
            print('点击了隐私政策');
            // TODO: Launch URL
          },
        );
      },
    );
  }

  @override
  Widget build(BuildContext context) {
    // 监听 AuthProvider 的状态，这样当 isChecked 变化时，UI 可以重建
    final authProvider = Provider.of<AuthProvider>(context);

    debugPrint(
      'LoginIndexPage build: isChecked = ${authProvider.isChecked}, isLoggedIn = ${authProvider.isLoggedIn}',
    );
    return AnnotatedRegion<SystemUiOverlayStyle>(
      value: const SystemUiOverlayStyle(
        statusBarColor: Colors.transparent, // 状态栏背景色
        statusBarIconBrightness: Brightness.light, // Android
        statusBarBrightness: Brightness.dark, // iOS
      ),
      child: Scaffold(
        backgroundColor: Colors.black,
        body: Scaffold(
          body: Stack(
            children: [
              Positioned.fill(
                child: Image.network(
                  'https://c-ssl.dtstatic.com/uploads/blog/202402/27/73SVJ94zfeXQdg1.thumb.1000_0.jpeg', // Replace with your actual image/video
                  fit: BoxFit.cover,
                ),
              ),
              Positioned(
                top: MediaQuery.of(context).padding.top + 60,
                left: 0,
                right: 0,
                child: Center(
                  child: Image.asset(
                    AppImages.VZ_DL_TEXT,
                    width: 254,
                    height: 87,
                  ),
                ),
              ),
              Positioned(
                bottom: 19 + MediaQuery.of(context).padding.bottom,
                left: 0,
                right: 0,
                child: Container(
                  padding: const EdgeInsets.symmetric(horizontal: 35),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.center,
                    children: [
                      _buildIconButton(
                        backgroundColor: Colors.white,
                        onPressed: () => {},
                        icon: AppImages.VZ_DL_PG,
                        text: "Sign in with Apple",
                        textColor: Color(0xff313033),
                      ),
                      SizedBox(height: 12),
                      _buildIconButton(
                        backgroundColor: Color(0xff39A0FF),
                        onPressed: () => {},
                        icon: AppImages.VZ_DL_FSBK,
                        text: "Sign in with Facebook",
                        textColor: Colors.white,
                      ),
                      SizedBox(height: 28),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          IconButton(
                            onPressed: () async {
                              if (!authProvider.isChecked) {
                                _showKindTipsDialog(context);
                              } else {
                                // 执行 Google 登录
                                bool success =
                                    await authProvider.signInWithGoogle();
                                if (success) {
                                  // Google 登录成功，跳转到 TabPage
                                  context.router.replaceAll([const TabRoute()]);
                                } else {
                                  // 登录失败，显示提示
                                  ScaffoldMessenger.of(context).showSnackBar(
                                    SnackBar(content: Text('Google 登录失败，请重试')),
                                  );
                                }
                              }
                            },
                            icon: Image.asset(
                              AppImages.VZ_DL_GG,
                              width: 44,
                              height: 44,
                            ),
                          ),
                          SizedBox(width: 28),
                          IconButton(
                            // 第二个IconButton (手机号登录)
                            onPressed: () {
                              if (authProvider.isChecked) {
                                context.router.push(LoginPhoneRoute());
                              } else {
                                _showKindTipsDialog(context);
                              }
                            },
                            icon: Image.asset(
                              AppImages.VZ_DL_SJH,
                              width: 44,
                              height: 44,
                            ),
                          ),
                        ],
                      ),
                      SizedBox(height: 29),
                      Row(
                        mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Checkbox(
                            value: authProvider.isChecked,
                            onChanged: (value) {
                              authProvider.setIsChecked(value ?? false);
                            },
                            activeColor: Colors.white,
                            checkColor: Colors.black,
                            side: const BorderSide(color: Colors.white),
                          ),
                          Expanded(
                            child: GestureDetector(
                              onTap: () {
                                // Handle navigation to User Service Agreement/Privacy Policy
                                print('Terms and Policy tapped');
                              },
                              child: RichText(
                                text: const TextSpan(
                                  text: 'I have read and agree to the ',
                                  style: TextStyle(
                                    color: Colors.white70,
                                    fontSize: 13,
                                  ),
                                  children: [
                                    TextSpan(
                                      text: 'User Service Agreement',
                                      style: TextStyle(
                                        decoration: TextDecoration.underline,
                                        color: Colors.white,
                                      ),
                                    ),
                                    TextSpan(text: ' and '),
                                    TextSpan(
                                      text: 'Privacy Policy',
                                      style: TextStyle(
                                        decoration: TextDecoration.underline,
                                        color: Colors.white,
                                      ),
                                    ),
                                  ],
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildIconButton({
    required VoidCallback onPressed,
    required String icon, // For custom image assets
    required String text,
    required Color backgroundColor,
    required Color textColor,
  }) {
    return Container(
      width: MediaQuery.of(context).size.width - 88,
      height: 56,
      decoration: BoxDecoration(
        color: backgroundColor,
        borderRadius: BorderRadius.circular(28),
      ),

      child: Stack(
        children: [
          Positioned(
            top: 0,
            bottom: 0,
            left: 24,
            child: Image.asset(icon, width: 24, height: 24),
          ),
          Center(
            child: Text(
              text,
              style: TextStyle(
                color: textColor,
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
            ),
          ),
        ],
      ),
    );
  }
}
